<template>
  <div class="sms-task-container">
    <!-- 主要内容区域 -->
    <el-row :gutter="20">
      <!-- 左侧：任务列表 -->
      <el-col :xs="24" :sm="24" :md="16" :lg="16">
        <el-card shadow="hover" class="task-list-card">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-s-order"></i>
              <span>群发任务列表</span>
            </div>
<!--            <div class="header-actions">-->
<!--              <el-button-->
<!--                type="primary"-->
<!--                icon="el-icon-plus"-->
<!--                size="mini"-->
<!--                @click="handleAdd"-->
<!--              >新增任务</el-button>-->
<!--              <el-button-->
<!--                type="danger"-->
<!--                plain-->
<!--                icon="el-icon-delete"-->
<!--                size="mini"-->
<!--                :disabled="multiple"-->
<!--                @click="handleDelete"-->
<!--              >删除</el-button>-->
<!--              <el-button-->
<!--                type="warning"-->
<!--                plain-->
<!--                icon="el-icon-download"-->
<!--                size="mini"-->
<!--                @click="handleExport"-->
<!--              >导出</el-button>-->
<!--            </div>-->
          </div>

          <!-- 筛选工具栏 -->
          <div class="filter-toolbar">
            <div class="left-section">
              <el-input
                v-model="queryParams.taskName"
                placeholder="搜索任务名称"
                clearable
                size="small"
                style="width: 200px"
                @keyup.enter.native="handleQuery"
              />
              <el-date-picker
                v-model="queryParams.scheduledTime"
                type="date"
                placeholder="计划发送日期"
                value-format="yyyy-MM-dd"
                size="small"
                style="width: 160px"
              />
            </div>
            <div class="right-section">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </div>
          </div>

          <!-- 任务表格 -->
          <el-table
            v-loading="loading"
            :data="SmsBulkTaskList"
            @selection-change="handleSelectionChange"
            @row-click="handleRowClick"
            ref="taskTable"
            border
            class="custom-table"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="任务ID" align="center" prop="taskId" width="180" />
            <el-table-column label="任务名称" align="left" prop="taskName" min-width="120" show-overflow-tooltip />
            <el-table-column label="任务状态" align="center" prop="taskStatus" width="100">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.taskStatus)">{{ getStatusText(scope.row.taskStatus) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="计划发送时间" align="center" prop="scheduledTime" width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.scheduledTime, '{y}-{m}-{d} {h}:{i}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="接收数/成功/失败" align="center" width="150">
              <template slot-scope="scope">
                <div>
                  <el-tooltip content="总接收数" placement="top">
                    <span class="stat-number">{{ scope.row.totalRecipients || 0 }}</span>
                  </el-tooltip>
                  <span class="stat-separator">/</span>
                  <el-tooltip content="成功数" placement="top">
                    <span class="stat-number success">{{ scope.row.successCount || 0 }}</span>
                  </el-tooltip>
                  <span class="stat-separator">/</span>
                  <el-tooltip content="失败数" placement="top">
                    <span class="stat-number error">{{ scope.row.failCount || 0 }}</span>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="签名名称" align="center" prop="signatureName" width="120" show-overflow-tooltip />
            <el-table-column label="模板名称" align="center" prop="templateName" width="120" show-overflow-tooltip />
            <el-table-column label="操作" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click.stop="handleUpdate(scope.row)"
                >修改</el-button>

                <el-button
                  v-if="scope.row.taskStatus === '1' || scope.row.taskStatus === '2'"
                  size="mini"
                  type="text"
                  icon="el-icon-close"
                  @click.stop="handleCancelSend(scope.row)"
                  style="color: #f56c6c;"
                >取消发送</el-button>

                <el-button
                  v-if="scope.row.taskStatus === '4'"
                  size="mini"
                  type="text"
                  icon="el-icon-refresh"
                  @click.stop="handleRestoreSend(scope.row)"
                  style="color: #67c23a;"
                >恢复发送</el-button>

                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click.stop="handleDelete(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
            class="custom-pagination"
          />

          <!-- 接收者列表 -->
          <div class="recipients-section" v-if="selectedTask">
            <div class="section-title">
              <div class="section-title-left">
                <i class="el-icon-user"></i>
                <span>{{ selectedTask.taskName }} 的接收者列表</span>
              </div>
              <el-tag type="info" size="small" v-if="taskRecipients && taskRecipients.length > 0">{{ taskRecipients.length }}个接收者</el-tag>
            </div>

            <div v-if="taskRecipients && taskRecipients.length > 0">
              <el-table
                :data="taskRecipients"
                border
                stripe
                size="small"
                style="width: 100%"
                height="300"
                class="recipients-table"
              >
                <el-table-column label="序号" type="index" width="50" align="center" />
                <el-table-column label="手机号码" prop="phoneNumber" min-width="120" />
                <el-table-column label="国家/地区" prop="countryCode" width="100" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.countryCode || '86' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="发送状态" prop="status" width="100" align="center">
                  <template slot-scope="scope">
                    <el-tag :type="getRecipientStatusType(scope.row.status)" size="mini">
                      {{ getRecipientStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="发送时间" prop="sendTime" width="160" align="center">
                  <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.sendTime, '{y}-{m}-{d} {h}:{i}') || '-' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="错误信息" prop="errorMsg" min-width="150" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span class="error-msg" v-if="scope.row.errorMsg">{{ scope.row.errorMsg }}</span>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else class="empty-recipients">
              <i class="el-icon-chat-dot-square"></i>
              <span>暂无接收者数据</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：任务详情 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8">
        <!-- 任务详情 -->
        <el-card shadow="hover" class="task-detail-card" v-if="selectedTask">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-document-copy"></i>
              <span>任务详情</span>
            </div>
            <div class="header-actions">
              <el-button
                type="text"
                icon="el-icon-refresh"
                @click="refreshTaskDetail(selectedTask)"
              >刷新详情</el-button>
            </div>
          </div>

          <el-descriptions :column="1" border>
            <el-descriptions-item label="任务名称">{{ selectedTask.taskName }}</el-descriptions-item>
            <el-descriptions-item label="任务状态">
              <el-tag :type="getStatusType(selectedTask.taskStatus)">{{ getStatusText(selectedTask.taskStatus)}}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="短信内容">
              <div class="task-content-preview">{{ selectedTask.smsContent }}</div>
            </el-descriptions-item>
            <el-descriptions-item label="计划发送时间">{{ parseTime(selectedTask.scheduledTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
            <el-descriptions-item label="实际发送时间">{{ parseTime(selectedTask.sendTime, '{y}-{m}-{d} {h}:{i}:{s}') || '未发送' }}</el-descriptions-item>
            <el-descriptions-item label="发送完成时间">{{ parseTime(selectedTask.completeTime, '{y}-{m}-{d} {h}:{i}:{s}') || '未完成' }}</el-descriptions-item>
            <el-descriptions-item label="发送统计">
              <div class="send-stats">
                <span class="stat-item">
                  <span class="stat-label">总接收人数：</span>
                  <span class="stat-value">{{ selectedTask.totalRecipients || 0 }}</span>
                </span>
                <span class="stat-item">
                  <span class="stat-label">发送成功：</span>
                  <span class="stat-value success">{{ selectedTask.successCount || 0 }}</span>
                </span>
                <span class="stat-item">
                  <span class="stat-label">发送失败：</span>
                  <span class="stat-value error">{{ selectedTask.failCount || 0 }}</span>
                </span>
                <span class="stat-item">
                  <span class="stat-label">每条价格：</span>
                  <span class="stat-value price">¥ {{ getUnitPrice(selectedTask).toFixed(3) }}</span>
                </span>
                <span class="stat-item">
                  <span class="stat-label">总费用：</span>
                  <span class="stat-value price highlight">¥ {{ getTotalCost(selectedTask).toFixed(2) }}</span>
                </span>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="创建人">{{ selectedTask.createUserName }}</el-descriptions-item>
          </el-descriptions>

          <!-- 消息预览 -->
          <div class="message-preview-section">
            <div class="section-title">
              <i class="el-icon-mobile-phone"></i>
              <span>消息预览</span>
            </div>

            <div class="phone-preview">
              <div class="phone-frame">
                <div class="phone-header">
                  <div class="phone-time">{{ currentTime }}</div>
                </div>
                <div class="phone-content">
                  <div class="message-bubble">
                    <div class="message-sender">【{{ selectedTask.signatureName || '云服务' }}】</div>
                    <div class="message-content">{{ selectedTask.smsContent }}</div>
                    <div class="message-time">{{ currentTime }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 无选中任务时的提示 -->
        <el-card shadow="hover" class="empty-selection-card" v-else>
          <div class="empty-selection">
            <i class="el-icon-s-order"></i>
            <span>请选择一个任务查看详情</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改短信群发任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body class="custom-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="签名ID" prop="signatureId">
          <el-select v-model="form.signatureId" placeholder="请选择签名" style="width: 100%">
            <el-option
              v-for="item in signatureOptions"
              :key="item.signatureId"
              :label="item.signatureName"
              :value="item.signatureId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板ID" prop="templateId">
          <el-select v-model="form.templateId" placeholder="请选择模板" style="width: 100%">
            <el-option
              v-for="item in templateOptions"
              :key="item.templateId"
              :label="item.templateName"
              :value="item.templateId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="短信内容">
          <el-input
            type="textarea"
            v-model="form.smsContent"
            :rows="4"
            placeholder="短信内容将根据所选模板自动生成"
            readonly
          />
        </el-form-item>
        <el-form-item label="计划发送时间" prop="scheduledTime">
          <el-date-picker
            v-model="form.scheduledTime"
            type="datetime"
            placeholder="请选择计划发送时间"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>

        <el-divider content-position="center">短信群发任务接收者信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSmsBulkTaskRecipient">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteSmsBulkTaskRecipient">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" icon="el-icon-upload2" size="mini">批量导入</el-button>
          </el-col>
        </el-row>
        <el-table :data="smsBulkTaskRecipientList" :row-class-name="rowSmsBulkTaskRecipientIndex" @selection-change="handleSmsBulkTaskRecipientSelectionChange" ref="smsBulkTaskRecipient" border size="small">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="手机号码" prop="phoneNumber" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.phoneNumber" placeholder="请输入接收手机号码" />
            </template>
          </el-table-column>
          <el-table-column label="国家/地区代码" prop="countryCode" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.countryCode" placeholder="国家/地区代码，默认86" />
            </template>
          </el-table-column>
          <el-table-column label="接收者变量参数" prop="variable1" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.variable1" placeholder="请输入变量参数" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBulkTask, getBulkTask, delBulkTask, addBulkTask, updateBulkTask } from "@/api/Sms/bulktask";
import { listSignatures } from "@/api/Sms/signatures";
import { listTemplate } from "@/api/Sms/template";
import {getPriceByUserId } from "@/api/Sms/SmsRecord"

export default {
  name: "SmsBulkTask",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSmsBulkTaskRecipient: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 短信群发任务表格数据
      SmsBulkTaskList: [],
      // 短信群发任务接收者表格数据
      smsBulkTaskRecipientList: [],
      // 选中任务的接收者列表
      taskRecipients: [],
      // 选中的任务
      selectedTask: null,
      // 签名选项
      signatureOptions: [],
      // 模板选项
      templateOptions: [],
      // 价格信息
      priceInfo: {
        smsNoticePrice: 0.080,
        smsSellPrice: 0.085,
        smsPicturePrice: 0.090,
        smsVoicePrice: 0.100
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        taskStatus: null,
        scheduledTime: null,
        sendTime: null,
        completeTime: null,
        totalRecipients: null,
        successCount: null,
        failCount: null,
        createUserId: null,
        createUserName: null,
        userId: this.$store.state.user.userId,
        signatureId: null,
        signatureName: null,
        templateId: null,
        templateName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        taskStatus: [
          { required: true, message: "任务状态不能为空", trigger: "change" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        signatureId: [
          { required: true, message: "签名不能为空", trigger: "change" }
        ],
        templateId: [
          { required: true, message: "模板不能为空", trigger: "change" }
        ],
        scheduledTime: [
          { required: true, message: "计划发送时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getSignatureOptions();
    this.getTemplateOptions();
    this.getPriceInfo();
  },
  computed: {
    // 当前时间
    currentTime() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    }
  },
  methods: {
    /** 获取价格信息 */
    async getPriceInfo() {
      try {
        const userId = this.$store.state.user.userId;
        console.log("正在获取价格信息，用户ID:", userId);

        const response = await getPriceByUserId(userId);
        console.log("价格信息接口响应:", response);

        if (response && response.code === 200 && response.data) {
          // 更新价格信息
          this.priceInfo = {
            smsNoticePrice: parseFloat(response.data.smsNoticePrice || 0.080),
            smsSellPrice: parseFloat(response.data.smsSellPrice || 0.085),
            smsPicturePrice: parseFloat(response.data.smsPicturePrice || 0.090),
            smsVoicePrice: parseFloat(response.data.smsVoicePrice || 0.100)
          };
        } else {
          console.warn("价格信息接口返回数据格式异常:", response);
        }
      } catch (error) {
        console.error("获取价格信息失败:", error);
        // 使用默认价格
        console.log("使用默认价格信息:", this.priceInfo);
      }
    },

    /** 查询短信群发任务列表 */
    getList() {
      this.loading = true;
      listBulkTask(this.queryParams).then(response => {
        this.SmsBulkTaskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 获取签名选项 */
    getSignatureOptions() {
      listSignatures({ pageSize: 100, auditStatus: 'successful' ,userId :this.$store.state.user.userId}).then(response => {
        this.signatureOptions = response.rows;
      });
    },

    /** 获取模板选项 */
    getTemplateOptions() {
      listTemplate({ pageSize: 100, auditStatus: 'successful' ,userId :this.$store.state.user.userId}).then(response => {
        this.templateOptions = response.rows;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        taskId: null,
        taskName: null,
        taskStatus: null,
        smsContent: null,
        scheduledTime: null,
        sendTime: null,
        completeTime: null,
        totalRecipients: null,
        successCount: null,
        failCount: null,
        createUserId: null,
        createUserName: null,
        createTime: null,
        updateTime: null,
        userId: null,
        signatureId: null,
        signatureName: null,
        templateId: null,
        templateName: null,
        recipientNumbers: null,
        templateParams: null,
        templateType: null
      };
      this.smsBulkTaskRecipientList = [];
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加短信群发任务";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const taskId = row.taskId || this.ids
      getBulkTask(taskId).then(response => {
        this.form = response.data;
        this.smsBulkTaskRecipientList = response.data.recipients || [];
        this.open = true;
        this.title = "修改短信群发任务";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.smsBulkTaskRecipientList = this.recipients;
          if (this.form.taskId != null) {
            updateBulkTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBulkTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const taskIds = row.taskId || this.ids;
      this.$modal.confirm('是否确认删除短信群发任务编号为"' + taskIds + '"的数据项？').then(function() {
        return delBulkTask(taskIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 短信群发任务接收者序号 */
    rowSmsBulkTaskRecipientIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },

    /** 短信群发任务接收者添加按钮操作 */
    handleAddSmsBulkTaskRecipient() {
      let obj = {};
      obj.batchNo = "";
      obj.phoneNumber = "";
      obj.countryCode = "86";
      obj.variable1 = "";
      obj.content = "";
      obj.status = "";
      obj.errorCode = "";
      obj.errorMsg = "";
      this.smsBulkTaskRecipientList.push(obj);
    },

    /** 短信群发任务接收者删除按钮操作 */
    handleDeleteSmsBulkTaskRecipient() {
      if (this.checkedSmsBulkTaskRecipient.length == 0) {
        this.$modal.msgError("请先选择要删除的短信群发任务接收者数据");
      } else {
        const smsBulkTaskRecipientList = this.smsBulkTaskRecipientList;
        const checkedSmsBulkTaskRecipient = this.checkedSmsBulkTaskRecipient;
        this.smsBulkTaskRecipientList = smsBulkTaskRecipientList.filter(function(item) {
          return checkedSmsBulkTaskRecipient.indexOf(item.index) == -1
        });
      }
    },

    /** 复选框选中数据 */
    handleSmsBulkTaskRecipientSelectionChange(selection) {
      this.checkedSmsBulkTaskRecipient = selection.map(item => item.index)
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('Sms/SmsBulkTask/export', {
        ...this.queryParams
      }, `SmsBulkTask_${new Date().getTime()}.xlsx`)
    },

    /** 处理行点击，显示任务详情和接收者列表 */
    handleRowClick(row) {
      this.selectedTask = row;
      this.getTaskRecipients(row.taskId);
    },

    /** 获取任务接收者列表 */
    getTaskRecipients(taskId) {
      getBulkTask(taskId).then(response => {
        this.taskRecipients = response.data.recipients || [];
      });
    },

    /** 刷新任务详情 */
    refreshTaskDetail(task) {
      if (task && task.taskId) {
        getBulkTask(task.taskId).then(response => {
          this.selectedTask = response.data;
          this.taskRecipients = response.data.recipients || [];
        });
      }
    },

    /** 获取任务状态类型对应的样式 */
    getStatusType(status) {
      switch (status) {
        case '0':
          return 'info';
        case '1':
          return 'primary';
        case '2':
          return 'warning';
        case '3':
          return 'success';
        case '4':
          return 'danger';
        case '5':
          return 'danger';
        default:
          return 'info';
      }
    },
    getStatusText(status) {
      switch (status) {
        case '0':
          return '草稿';
        case '1':
          return '待发送';
        case '2':
          return '发送中';
        case '3':
          return '已完成';
        case '4':
          return '已取消';
        case '5':
          return '失败';
        default:
          return status || '未知';
      }
    },

    /** 获取接收者状态类型对应的样式 */
    getRecipientStatusType(status) {
      switch (status) {
        case '0':
          return 'danger';
        case '1':
          return 'success';
        case '2':
          return 'success';
        case '3':
          return 'warning';
        case 'failed':
          return 'danger';
        default:
          return 'info';
      }
    },

    /** 获取接收者状态文本 */
    getRecipientStatusText(status) {
      switch (status) {
        case '0':
          return '未发送';
        case '1':
          return '已发送';
        case '2':
          return '发送成功';
        case '3':
          return '发送失败';
        default:
          return status || '未知';
      }
    },

    /** 取消发送按钮操作 */
    handleCancelSend(row) {
      const taskName = row.taskName || row.taskId;
      this.$modal.confirm(`是否确认取消发送任务"${taskName}"？取消后任务状态将变为已取消。`, '确认取消发送', {
        confirmButtonText: '确定取消',
        cancelButtonText: '暂不取消',
        type: 'warning'
      }).then(() => {
        // 创建要更新的数据对象
        const updateData = {
          taskId: row.taskId,
          taskStatus: '4'  // 设置为已取消状态
        };

        return updateBulkTask(updateData);
      }).then(() => {
        // 刷新列表
        this.getList();
        // 如果当前选中的是被取消的任务，也要刷新详情
        if (this.selectedTask && this.selectedTask.taskId === row.taskId) {
          this.refreshTaskDetail(this.selectedTask);
        }
        this.$modal.msgSuccess("任务已成功取消发送");
      }).catch((error) => {
        if (error !== 'cancel') {
          console.error('取消发送失败:', error);
          this.$modal.msgError("取消发送失败，请稍后重试");
        }
      });
    },

    /** 恢复发送按钮操作 */
    handleRestoreSend(row) {
      const taskName = row.taskName || row.taskId;
      this.$modal.confirm(`是否确认恢复发送任务"${taskName}"？恢复后任务状态将变为待发送。`, '确认恢复发送', {
        confirmButtonText: '确定恢复',
        cancelButtonText: '暂不恢复',
        type: 'warning'
      }).then(() => {
        // 创建要更新的数据对象
        const updateData = {
          taskId: row.taskId,
          taskStatus: '1'  // 设置为待发送状态
        };

        return updateBulkTask(updateData);
      }).then(() => {
        // 刷新列表
        this.getList();
        // 如果当前选中的是被恢复的任务，也要刷新详情
        if (this.selectedTask && this.selectedTask.taskId === row.taskId) {
          this.refreshTaskDetail(this.selectedTask);
        }
        this.$modal.msgSuccess("任务已成功恢复发送");
      }).catch((error) => {
        if (error !== 'cancel') {
          console.error('恢复发送失败:', error);
          this.$modal.msgError("恢复发送失败，请稍后重试");
        }
      });
    },

    /** 获取每条价格 */
    getUnitPrice(task) {
      if (!task) return 0;

      console.log("SmsBulkTask 价格计算:");
      console.log("当前价格信息:", this.priceInfo);
      console.log("任务模板类型:", task.templateType);

      // 根据模板类型获取对应价格
      if (task.templateType === '1' || task.templateType === 1) {
        // 通知消息
        console.log("使用通知消息价格:", this.priceInfo.smsNoticePrice);
        return this.priceInfo.smsNoticePrice;
      } else if (task.templateType === '2' || task.templateType === 2) {
        // 营销消息
        console.log("使用营销消息价格:", this.priceInfo.smsSellPrice);
        return this.priceInfo.smsSellPrice;
      } else if (task.templateType === '3' || task.templateType === 3) {
        // 图片消息
        console.log("使用图片消息价格:", this.priceInfo.smsPicturePrice);
        return this.priceInfo.smsPicturePrice;
      } else if (task.templateType === '4' || task.templateType === 4) {
        // 语音消息
        console.log("使用语音消息价格:", this.priceInfo.smsVoicePrice);
        return this.priceInfo.smsVoicePrice;
      }

      // 默认使用通知消息价格
      console.log("使用默认价格:", this.priceInfo.smsNoticePrice);
      return this.priceInfo.smsNoticePrice;
    },

    /** 获取总费用 */
    getTotalCost(task) {
      if (!task) return 0;

      const unitPrice = this.getUnitPrice(task);
      const totalRecipients = task.totalRecipients || 0;
      // 计算总消息条数（假设每个接收者发送1条消息）
      const totalMessages = totalRecipients;

      const totalCost = totalMessages * unitPrice;
      console.log(`费用计算: ${totalMessages} 条消息 × ¥${unitPrice} = ¥${totalCost.toFixed(2)}`);

      return totalCost;
    }
  }
};
</script>

<style scoped>
.sms-task-container {
  padding: 0px;
  background-color: #fff;
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 15px;
  display: flex;
  align-items: center;
}

.header-title i {
  margin-right: 5px;
  font-size: 16px;
  color: #409EFF;
}

/* 筛选工具栏样式 */
.filter-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.left-section {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.right-section {
  display: flex;
  gap: 10px;
}

/* 任务列表卡片样式 */
.task-list-card {
  margin-bottom: 20px;
  border-radius: 4px;
}

/* 任务详情卡片样式 */
.task-detail-card {
  margin-bottom: 20px;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.task-content-preview {
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  line-height: 1.5;
  word-break: break-all;
}

/* 发送统计样式 */
.send-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-label {
  min-width: 80px;
  color: #606266;
}

.stat-value {
  font-weight: 500;
}

.stat-value.success {
  color: #67c23a;
}

.stat-value.error {
  color: #f56c6c;
}

.stat-value.price {
  color: #409eff;
  font-weight: 600;
}

.stat-value.price.highlight {
  color: #f56c6c;
  font-size: 16px;
}

.stat-number {
  font-weight: 500;
}

.stat-number.success {
  color: #67c23a;
}

.stat-number.error {
  color: #f56c6c;
}

.stat-separator {
  margin: 0 5px;
  color: #dcdfe6;
}

/* 接收者列表样式 */
.recipients-section {
  margin-top: 20px;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 15px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.section-title-left {
  display: flex;
  align-items: center;
  gap: 5px;
}

.recipients-table {
  border-radius: 4px;
  overflow: hidden;
}

/* 无选中任务时的样式 */
.empty-selection-card {
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.empty-selection {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
}

.empty-selection i {
  font-size: 48px;
  margin-bottom: 16px;
}

/* 无接收者数据时的样式 */
.empty-recipients {
  padding: 30px 0;
  text-align: center;
  color: #909399;
}

.empty-recipients i {
  font-size: 36px;
  margin-bottom: 10px;
  display: block;
}

/* 自定义表格样式 */
.custom-table {
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 自定义分页器样式 */
.custom-pagination {
  margin-top: 20px;
  text-align: right;
}

/* 自定义对话框样式 */
.custom-dialog >>> .el-dialog__header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.custom-dialog >>> .el-dialog__title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.custom-dialog >>> .el-dialog__body {
  padding: 20px;
}

.custom-dialog >>> .el-dialog__footer {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
}

.mb8 {
  margin-bottom: 8px;
}

/* 消息预览样式 */
.message-preview-section {
  margin-top: 20px;
}

.phone-preview {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.phone-frame {
  width: 240px;
  height: 400px;
  border: 8px solid #303133;
  border-radius: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background-color: #f0f0f0;
}

.phone-header {
  height: 40px;
  background-color: #303133;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}

.phone-content {
  flex: 1;
  padding: 12px;
  overflow-y: auto;
}

.message-bubble {
  background-color: #fff;
  border-radius: 10px;
  padding: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-sender {
  font-weight: 500;
  margin-bottom: 8px;
  color: #409eff;
}

.message-content {
  line-height: 1.5;
  word-break: break-all;
}

.message-time {
  text-align: right;
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.error-msg {
  color: #f56c6c;
}
</style>
